import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useContext, useEffect, useMemo, useState } from 'react';
import { ApplyControllerContext } from '../common';
import { applyInfoEffect, getDescrConfig, getPackTableColumns } from '../mconfig';
import { DescriptionsType, useDescriptionsType } from '@/components/DescriptionsType';
import { getColorTextLoadMap, getKeyRouter } from '@/utils';
import UpdatePackList from '../mview/UpdatePackList';
import { Drawer, Table, Tooltip, message } from 'antd';
import { handleOneObjectData, setTableRowClassName, supplyWayList } from '../common/Format';
import { ApplyUpdateService } from '../services/UpdateService';
import _ from 'lodash';
import { history } from 'umi';
import { EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';
import { renderFileFunc } from '../../Acommon';
import { formatDecimal } from '@/common';

export const DetailInfoCenterViewMainOA: React.FC = () => {
  /** 获取上下文 */
  const { styleFixCls, applyDetailInfo, applyForm, curRes } = useContext(ApplyControllerContext);

  // API 接口
  const { getPackService } = ApplyUpdateService();

  const [packList, setPackList] = useState([]);

  /** 获取标包接口 */
  const { getPackRun } = getPackService();

  const [isShowUpload, setIsShowUpload] = useState<number>(0);

  /** 是否显示对应的表格 */
  const [isShowObj, setIsShowObj] = useState<Record<string, any>>({
    isShowUpload: 0, // 标的来源
    isShowOther: 0, // 其他
    isShowCommon: 0, // 是否共性
    isShowPlatform: 0, // 是否平台
    isShowCategory: 0, // 采购类别
    isShowConsign: 0, // 是否会签
    isShowMeeting: 0, // 是否上会
  });

  const fetchGetPack = async (params: Record<string, any>) => {
    let { obj } = await getPackRun(params);

    /** 标包数据排序 - 创建时间最早的在第一个 */
    obj?.sort((a, b) => {
      var dateA: any = new Date(a?.createTime);
      var dateB: any = new Date(b?.createTime);
      return dateA - dateB;
    });

    /** obj = 包的集合 */
    obj?.forEach((item) => {
      /** mpurchaseSourceMaterials = 包下面的标的集合 */
      item?.mpurchaseSourceMaterials?.forEach((ite) => {
        /** mmaterial = 物料的详细数据 */
        if (ite?.materialType) {
          ite.fullName = ite?.mmaterial?.fullName; // 标的名称
          // ite.supplyTypeName = ite?.mmaterial?.supplyTypeName; // 标的类型 [翻译]
          // ite.supplyType = ite?.mmaterial?.supplyType; // 标的类型
          ite.specInfo = ite?.mmaterial?.specInfo; // 规格型号（参数）
          ite.needParams = ite?.mmaterial?.specInfo; /** 规格要求（替换） */
          ite.supplyKindName = ite?.mmaterial?.materialTypeName; // 标的名称
          ite.supplyKind = ite?.mmaterial?.materialType; // 标的名称 【修改= materialTypeName -> materialType】
        } else {
          ite.needParams = ite?.specInfo; /** 规格要求（替换） */
        }

        /** 操作会修改expectNum, 要另外保存一份【1，接口请求回来的标包，2，锁定数量要扣除】 */
        ite.expectNum_s = ite?.expectNum;

        /** 实施物料id重新给一个字段，用于编辑 */
        ite.CarryID = ite?.id;
      });

      item.mpurchaseNeedMaterials = item?.mpurchaseSourceMaterials;
      item.SourceData = item?.mpurchaseSourceMaterials || []; // 一份源数据
      delete item?.mpurchaseSourceMaterials;
    });
    setPackList(obj);
  };

  const fetchFindApply = () => {
    /** 申请详情中是否有标包信息 && 获取标包接口调用 */
    if (applyDetailInfo?.mpurchasePacks && applyDetailInfo?.mpurchasePacks?.length) {
      let packIds = applyDetailInfo?.mpurchasePacks?.map((item) => item?.id).join(',');
      fetchGetPack({ packIds });
    }
  };

  useEffect(() => {
    fetchFindApply();
  }, []);

  /** 初始化数据 */
  applyInfoEffect(applyDetailInfo, applyForm);

  useEffect(() => {
    setIsShowUpload(applyDetailInfo?.supplyWay);
    if (Object.keys(applyDetailInfo).length) {
      setIsShowObj({
        isShowUpload: applyDetailInfo?.supplyWay || 0, // 标的来源
        isShowOther: applyDetailInfo?.purchContent || 0, // 是否展示其他
        isShowCommon: applyDetailInfo?.commonFlag || 0, // 共性
        isShowPlatform: applyDetailInfo?.platformFlag || 0, // 平台
        isShowCategory: applyDetailInfo?.purchCategory || 0, // 采购类别
        isShowConsign: applyDetailInfo?.consignFlag || 0, // 会签
        isShowMeeting: applyDetailInfo?.meetingFlag || 0, // 上会
      });
    }
  }, [applyDetailInfo]);
  const [open, setOpen] = useState<Record<string, any>>({}); /**抽屉的显示*/

  /** 申请单信息 */
  const { config } = getDescrConfig({ isShowUpload, isShowObj });

  /** 标包信息 */
  const [configs, methods] = useDescriptionsType({
    labelWidth: 240,
    // isShowNumTitle:false,
    schemas: [
      {
        key: 'applyInfoDes',
        title: '基本信息',
        isNoShowNum: true,
        fieldChildren: [
          {
            label: '标包名称',
            field: 'packName',
            component: 'Render',
            slotRender: (text: string) => {
              return <span style={{ marginLeft: '8px' }}>{text || '--'}</span>;
            },
          },
          {
            label: '包号',
            field: 'packCode',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          // {
          //   label: '采购类别',
          //   field: 'supplyTypeName',
          //   component: 'Render',
          //   slotRender: (text: string) => {
          //     const { colorText, color } = getColorTextLoadMap(text);
          //     if (colorText) {
          //       return <div style={{ color, paddingLeft: '8px' }}>{colorText || '--'}</div>;
          //     } else {
          //       return <div style={{ color: '#c4c4c3', paddingLeft: '8px' }}>自动带出</div>;
          //     }
          //   },
          // },
          {
            label: '预算金额',
            field: 'expectSum',
            placeholder: '自动带出',
            component: 'Render',
            disabled: true,
            contentAfter: '元',
            slotRender: (text) => {
              return <div style={{ paddingLeft: '8px' }}>{formatDecimal(text)}</div>;
            },
          },
          {
            label: '标的来源',
            field: 'supplyWay',
            placeholder: '自动带出',
            component: 'Select',
            colSpan: 1,
            options: supplyWayList,
            disabled: true,
            fieldNames: {
              label: 'name',
              value: 'value',
            },
          },
          {
            label: '采购组织类型',
            field: 'procureOrgName',
            component: 'Render',
            placeholder: '自动带出',
            disabled: false,
            slotRender: (text: string) => {
              const { colorText, color } = getColorTextLoadMap(text);
              if (colorText) {
                return <div style={{ color, paddingLeft: '8px' }}>{colorText || '--'}</div>;
              } else {
                return <div style={{ color: '#c4c4c3', paddingLeft: '8px' }}>自动带出</div>;
              }
            },
          },
          {
            label: '拟定采购方式',
            placeholder: '自动带出',
            field: 'procureRealName',
            component: 'Render',
            slotRender: (text: string) => {
              const { colorText, color } = getColorTextLoadMap(text);
              if (colorText) {
                return <div style={{ color, paddingLeft: '8px' }}>{colorText || '--'}</div>;
              } else {
                return <div style={{ color: '#c4c4c3', paddingLeft: '8px' }}>自动带出</div>;
              }
            },
          },

          {
            label: '采购方式变更申请单',
            field: 'changeID',
            component: 'Render',
            colSpan: 2,
            slotRender: (text) => {
              return (
                <div style={{ paddingLeft: '8px' }}>
                  {text ? (
                    <Tooltip title={'查看采购方式变更申请单'}>
                      <a>
                        <EyeOutlined
                          onClick={() => {
                            // if (curRes?.['/purchaseSourceChangeController/getSourceChangeById/{id}/{currentUserID}']) {
                            //   history.push({
                            //     pathname: `/purchaseSourceChangeController/getSourceChangeById/{id}/{currentUserID}/:${getKeyRouter()}${getKeyRouter()}`,
                            //     state: {
                            //       info: { changeID: text },
                            //       type: 'view',
                            //     },
                            //   });
                            // } else {
                            message?.error('请登录系统再查看！');
                            // }
                          }}
                        />
                      </a>
                    </Tooltip>
                  ) : (
                    <Tooltip title="暂无采购方式变更申请单">
                      <a>
                        <EyeInvisibleOutlined />
                      </a>
                    </Tooltip>
                  )}
                </div>
              );
            },
          },
          {
            label: '意向公开名称',
            field: 'intentName',
            component: 'Input',
            placeholder: '--',
            disabled: true,
          },
          {
            label: '意向公开时间',
            field: 'intentTime',
            component: 'Input',
            placeholder: '--',
            disabled: true,
          },
          {
            label: '技术规范',
            field: 'skillNormURL',
            placeholder: '请上传技术规范',
            component: 'Render',
            colSpan: open?.record?.supplyWay && open?.record?.supplyWay == 1 ? 1 : 0,
            // required: true,
            slotRender: () => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: open?.record || {},
                    fileName: 'skillNormURL',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '调研报告',
            field: 'researchReportURL',
            placeholder: '请上传调研报告',
            component: 'Render',
            colSpan: open?.record?.supplyWay && open?.record?.supplyWay == 1 ? 1 : 0,
            // required: true,
            slotRender: () => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: open?.record || {},
                    fileName: 'researchReportURL',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '是否进口',
            field: 'importFlag',
            component: 'Render',
            colSpan: open?.record?.supplyWay && open?.record?.supplyWay == 1 ? (!open?.record.importFlag ? 2 : 1) : 0,
            slotRender: (text: any = 0) => {
              return <span style={{ marginLeft: 8 }}>{text == 0 ? '否' : '是'}</span>;
            },
          },
          {
            label: '进口专业人员论证意见',
            field: 'needImportURL',
            placeholder: '请上传进口专业人员论证意见',
            component: 'Render',
            colSpan: 1,
            ishidden: open?.record?.supplyWay && open?.record?.supplyWay == 1 && open?.record?.importFlag == 1 ? false : true,
            // required: true,
            slotRender: () => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: open?.record || {},
                    fileName: 'needImportURL',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '是否单一来源',
            field: 'singleFlag',
            component: 'Render',
            colSpan: open?.record?.supplyWay && open?.record?.supplyWay == 1 ? (!open?.record.singleFlag ? 2 : 1) : 0,
            slotRender: (text: any = 0) => {
              return <span style={{ marginLeft: 8 }}>{text == 0 ? '否' : '是'}</span>;
            },
          },
          {
            label: '单一来源论证意见',
            field: 'needSingleURL',
            placeholder: '请上传单一来源论证意见',
            component: 'Render',
            colSpan: 1,
            ishidden: open?.record?.supplyWay && open?.record?.supplyWay == 1 && open?.record?.singleFlag == 1 ? false : true,
            // required: true,
            slotRender: () => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: open?.record || {},
                    fileName: 'needSingleURL',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '相关附件',
            field: 'relatedUrl',
            placeholder: '请上传相关附件',
            component: 'Render',
            colSpan: 2,
            slotRender: () => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: open?.record || {},
                    fileName: 'relatedUrl',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '需求论证意见',
            field: 'needProofURL',
            placeholder: '请上传需求论证意见',
            component: 'Render',
            colSpan:
              open?.record?.supplyWay == 1 && open?.record?.expectSum && Number(open?.record?.expectSum) >= 500000
                ? Number(open?.record?.expectSum) >= 1000000
                  ? 1
                  : 2
                : 0,
            // required: true,
            slotRender: () => {
              return (
                <span style={{ marginLeft: 8 }}>
                  {renderFileFunc({
                    record: open?.record || {},
                    fileName: 'needProofURL',
                    downloadAddress: '/purchaseApplyController/downloadFile',
                    returnStr: '/',
                  })}
                </span>
              );
            },
          },
          {
            label: '是否通过主任办公室会议',
            field: 'directorMeetingFlag',
            placeholder: '请上传是否通过主任办公室会议',
            component: 'Render',
            colSpan: open?.record?.supplyWay == 1 && open?.record?.expectSum && Number(open?.record?.expectSum) >= 1000000 ? 1 : 0,
            // required: true,
            slotRender: (text: any = 0) => {
              return <span style={{ marginLeft: 8 }}>{text == 0 ? '否' : '是'}</span>;
            },
          },
        ],
      },
    ],
  });

  const dataMemo = useMemo(() => {
    let temp = _.cloneDeep(open?.record);
    const find: any = packList?.find((item: any) => item?.id == temp?.id);
    if (open?.isShow) {
      let data = handleOneObjectData(find?.mpurchaseNeedMaterials);
      return data;
    } else {
      return [];
    }
  }, [open?.isShow, open?.record, packList]);

  /**改变显示抽屉状态*/
  const onSetOpen = (res) => {
    methods?.setFieldsValue(res?.record);
    setOpen(res);
  };
  return (
    <>
      <div className="commonTabsBodyDom">
        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
          <ScrollBarLayout style={{ padding: '5px 100px' }}>
            <div className={`${styleFixCls}infoViewOA-centerBodyTitleBox`}>{applyDetailInfo?.applyName}</div>
            <DescriptionsType config={config} />
            {/* <UpdatePackView formName={applyForm} packList={applyDetailInfo?.mpurchasePacks} jumpSource={jumpSource} /> */}
            <UpdatePackList packList={applyDetailInfo?.mpurchasePacks} onSetOpen={onSetOpen} />
            <Drawer
              title="标包信息"
              placement="right"
              closable={false}
              onClose={() => setOpen({})}
              open={open?.isShow}
              getContainer={false}
              style={{ position: 'absolute' }}
              width={document.body?.clientWidth * 0.5}
              bodyStyle={{
                padding: 0,
                overflow: 'hidden',
                display: 'flex',
                flexDirection: 'column',
              }}
              className={'packInfoDrawer'}
            >
              <ScrollBarLayout style={{ padding: '10px' }}>
                <DescriptionsType config={configs} />
                <div className={'apply-update-title-divClassName'}>二、标包物料</div>
                {/* ${prefixCls}-steps-pack-table */}
                <div className={`list-table`} style={{ height: '100%', overflow: 'hidden' }}>
                  <Table
                    bordered
                    size="small"
                    rowKey={'materialID'}
                    pagination={false}
                    rowClassName={setTableRowClassName}
                    scroll={{ x: 1000, y: 1000 }}
                    dataSource={dataMemo}
                    rowSelection={undefined}
                    columns={getPackTableColumns({
                      applyDetailInfo,
                      finallyType: 'view',
                      changeTargetInfo: () => {},
                      onRemove: () => {},
                    })}
                  />
                </div>
              </ScrollBarLayout>
            </Drawer>
          </ScrollBarLayout>
        </div>
      </div>
    </>
  );
};
